package com.talent.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.talent.util.StringUtil;


@Controller
@RequestMapping("dbcmd")
public class DbCommand {
	private final Logger logger = Logger.getLogger(DbCommand.class);

	private String dbUser = "root";
	private String dbPwd = "";

	public static HttpSession getSession() {
		HttpSession session = null;
		try {
			session = getRequest().getSession();
		} catch (Exception e) {
		}
		return session;
	}

	public static HttpServletRequest getRequest() {
		ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes();
		return attrs.getRequest();
	}
	
	/**
	 * read property
	 */
	private void readProperty() {
		Properties prop =  new  Properties();
		String path = getClass().getResource("/").getPath();
		path = path.substring(1, path.indexOf("classes"));
		try  {    
			prop.load(new FileInputStream("/"+path+"jdbc.properties"));
			
            dbUser = prop.getProperty("username").trim();    
            dbPwd = prop.getProperty("password").trim();    
        }  catch  (Exception e) {
        	logger.debug("readProperty exception" + e.getMessage());
            e.printStackTrace();    
        }
	}

	@RequestMapping("/db.do")
	public ModelAndView dbCommand() {
		readProperty();
		
		ModelAndView mv = new ModelAndView();
		mv.setViewName("db_command");
		return mv;
	}
	
	/**
	 * 备份
	 * @return
	 */
	@RequestMapping("/backup.do")
	public String dbBackup() {
		logger.debug("dbBackup...");
		String strFilePath = "/usr/local/back/db_38s" + StringUtil.getStrDate() + ".sql";
		
		String strCmd = "mysqldump -u "+dbUser+" -p"+dbPwd+" --databases db_38s > "+ strFilePath;
		logger.debug("dbBackup strCmd=" + strCmd);
		return execCommand(strCmd);
	}
	
	/**
	 * 恢复
	 * @return
	 */
	@RequestMapping("/restore.do")
	public String dbRestore() {
		String strFilePath = "/usr/local/back/db_38s_backup.sql";
		try {
			strFilePath = getRestoreFilePath();
		} catch (Exception ex) {
			logger.debug("get restore file exception" + ex.getMessage());
			ex.printStackTrace();
		}
		String strCmd = "mysql -u "+dbUser+" -p"+dbPwd+" -h 127.0.0.1 db_38s < " + strFilePath;
		logger.debug("dbRestore strCmd=" + strCmd);
		return execCommand(strCmd);
	}
	
	private String getRestoreFilePath() throws Exception{
		String strFilePath = "/usr/local/back/db_38s" + StringUtil.getStrDate() + ".sql";
		File file = new File(strFilePath);
		if(file.exists()) {
			return strFilePath;
		} else if(new File("/usr/local/back/db_38s" + StringUtil.getPreDayDate(-1) + ".sql").exists()){
			return "/usr/local/back/db_38s" + StringUtil.getPreDayDate(-1) + ".sql";
		} else if(new File("/usr/local/back/db_38s" + StringUtil.getPreDayDate(-2) + ".sql").exists()) {
			return "/usr/local/back/db_38s" + StringUtil.getPreDayDate(-2) + ".sql";
		} else if(new File("/usr/local/back/db_38s" + StringUtil.getPreDayDate(-3) + ".sql").exists()) {
			return "/usr/local/back/db_38s" + StringUtil.getPreDayDate(-3) + ".sql";
		} else {
			return "/usr/local/back/db_38s_backup.sql";
		}
	}
	
	private String execCommand(String strCmd) {
		String strRel = "success";
		try {
			Runtime runtime = Runtime.getRuntime();
			
			String[] command = new String[]{"/bin/bash", "-c", strCmd};
			Process process = runtime.exec(command);
			
			//print out running result
			InputStreamReader in = new InputStreamReader(process.getInputStream());
			BufferedReader br = new BufferedReader(in);
		    String line = null;
		    while((line = br.readLine()) != null){
		        logger.debug("Running result=" + line);
		    }
		    br.close();
		    in.close();
		    strRel = (line != null) ? strRel+","+line : "success";
		    
		    //print out error messages
		    InputStreamReader in2 = new InputStreamReader(process.getErrorStream());
		 	BufferedReader br2 = new BufferedReader(in2);
		 	String line2 = null;
		 	while((line2 = br2.readLine()) != null){
		        logger.debug("Running error=" + line2);
		 	}
		 	br2.close();
		 	in2.close();
		 	strRel = (line2 != null) ? "error"+","+line2 : "error";
			
		} catch (Exception ex) {
			ex.printStackTrace();
			strRel = "error,Exception:" + ex.getMessage();
		}
		return strRel;
	}

}
